# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root):
        # res = []
        # stack = [root]
        # while stack:
        #     tmp = []
        #     lenth = len(stack)
        #     for i in range(lenth):
        #         node = stack.pop()
        #         if not node: continue
        #         tmp.append(node.val)
        #         stack.insert(0, node.left)
        #         stack.insert(0, node.right)
        #     if tmp:
        #         res.append(tmp)
        # return res
        res = []
        def dfs(level):
            tmp = []
            if not level: return
            for i in range(len(level)):
                node = level.pop()
                if not node: continue
                tmp.append(node.val)
                level.insert(0, node.left)
                level.insert(0, node.right)
            if tmp:
                res.append(tmp)
            dfs(level)
        dfs([root])
        return res